/**
 * Created by Aranld on 2017/5/11.
 */
const schedule = require('node-schedule');
const log = require('../util/log.js');
const gameUser = require('./gameUser.js');
const variable = require('../config/variable.js');
const request = require('../util/request.js');
var mem = require('../util/mem.js');

module.exports = interval;

function interval() {
    // 建立一个时间循环的默认规则
    var rule = new schedule.RecurrenceRule();
    // 增加一个每秒执行的内容
    var times = [];
    for (var i = 1; i < 60; i++) {
        times.push(i);
    }
    rule.second = times;
    // 开始动作
    schedule.scheduleJob(rule, function () {
        deleteRoom();
    });
}

function deleteRoom() {
    for (var i in mem.games) {
        var game = mem.games[i];
        var del = true;
        for (var j in game.id) {
            if (mem.gamePlayers[game.id[j]] && mem.gamePlayers[game.id[j]].line != 'off') {
                del = false;
            }
        }
        if (del) {
            var escapeGold = 0;
            if (game.ddz && game.ddz.getBaseScore() > 0 && game.ddz.getMultiple() > 0) {
                escapeGold += game.ddz.getBaseScore() * game.ddz.getMultiple() * variable.config.killGamePunish;
                escapeGold += game.ddz.getTicket();
            } else {
                escapeGold += game.ddz.getTicket();
            }

            for (var j = 0; j < 3; j++) {
                if (!mem.gamePlayers[game.id[j]]) {
                    continue;
                }

                if (!mem.gamePlayers[game.id[j]].robot) {
                    gameUser.escapee(game.id[j], mem.gamePlayers[game.id[j]].cid, mem.gamePlayers[game.id[j]].uuid, escapeGold);
                } else {
                    gameUser.robotEscapee(game.id[j], escapeGold);
                }
                delete mem.gamePlayers[game.id[j]];
            }
            if (game.ddz) {
                game.ddz.close();
                game.ddz = null;
            }
            delete mem.games[i];
            var param = {};
            param.gameId = i;
            request.delGame(param, function () {
            });
            log.p('kill room:' + i);
        }
    }
}